
{
    let labelType = 'PQ'; /** PQ内箱， CQ外箱 */
    const labelIds = [];
    let originList = [];
    const rootVue = document.querySelector('body .site-wrapper').__vue__;
    let loading;

    window.__Add_Label__ = () => loadXLSX(async () => {
        getLabel().then(() => {
            rootVue.$message({ message: '处理完成！', type: 'success', duration: 30 * 1000, showClose: true });
            loading?.close();
            openLabelPage();
        }).catch(err => {
            loading?.close();
            console.error(err);
            rootVue.$message({ message: err.message || err, type: 'error', duration: 30 * 1000, showClose: true });

            if (labelIds.length) {
                rootVue.$confirm(`已处理 ${labelIds.length} 条数据，是否打印？`, '提示').then(() => {
                    openLabelPage();
                })
            }
        })
    });

    async function getLabel() {
        const fileInput = createFileInput();
        const jsonData = await setupFileReader(fileInput);


        await rootVue.$confirm(`
            <div>
                <label class='my-radio' style="padding-right:25px;"><input type="radio" name="labelType" value="PQ" checked> PQ内箱 </label>
                <label class='my-radio'><input type="radio" name="labelType" value="CQ"> CQ外箱 </label>
            </div>
            `, '提示', {
            dangerouslyUseHTMLString: true
        });
        labelType = document.querySelector('.my-radio input:checked').value;

        const inputData = {};
        jsonData.forEach(row => {
            /** PQ内箱 */
            if (labelType === 'PQ') {
                if (!row['外箱信息'] || !row['批次号'] || !row['DateCode']) return;
                const key = row['外箱信息'] + '_' + row['批次号'] + '_' + row['DateCode'];
                if (inputData[key]) {
                    inputData[key]['标签数量']++;
                } else {
                    inputData[key] = {
                        '标签数量': 1,
                        '数量': parseInt(row['数量']),
                        '批次号': row['批次号'],
                        'DateCode': row['DateCode'],
                        '客户物料代码': row['客户物料代码'],
                        '外箱信息': row['外箱信息'],
                        '产地': row['产地'],
                        '原DC': row['原DC'],
                        '备注': row['备注'],
                    };
                }
            } else {
                if (!row['外箱信息']) return;
                const key = row['外箱信息'];
                const date = (row['DateCode'] || '').toString();
                const time = new Date(`${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)} 00:00:00`).getTime();
                if (inputData[key]) {
                    inputData[key]['数量'] += parseInt(row['数量']);
                    if (time < inputData[key]['最早日期']) {
                        inputData[key]['最早日期'] = time;
                        inputData[key]['row'] = row;
                    }
                } else {
                    inputData[key] = {
                        '标签数量': 1,
                        '数量': parseInt(row['数量']),
                        '最早日期': time,
                        row,
                    };
                }
            }
        });
        if (labelType === 'CQ') {
            Object.values(inputData).forEach(row => {
                row['批次号'] = row.row['批次号'];
                row['DateCode'] = row.row['DateCode'];
                row['客户物料代码'] = row.row['客户物料代码'];
                row['外箱信息'] = row.row['外箱信息'];
                row['产地'] = row.row['产地'];
                row['原DC'] = row.row['原DC'];
                row['备注'] = row.row['备注'] || null;
                delete row.row;
                delete row['最早日期'];
            })
        }

        console.table(inputData);

        const originRes = await rootVue.$api.srm.listOrigin({
            pageNum: 1,
            pageSize: 10000
        });
        originList = originRes.records || [];
        await rootVue.$confirm(getTableHtml(inputData), '提示', {
            customClass: 'my-table',
            dangerouslyUseHTMLString: true
        });

        loading = rootVue.$loading({
            lock: !0,
            text: "数据处理中（0%）...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
        });

        const keys = Object.keys(inputData);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            const row = inputData[key];

            const item = await rootVue.$api.srm.listNewLabelCodeItem({
                current: 1,
                size: 10,
                itemCode: row['客户物料代码'],
                pageNum: 1,
                pageSize: 10
            }).then(function (t) {
                const itemList = t ? t.records : [];
                return itemList[0];
            });
            if (!item) throw new Error(`没找到客户物料代码(${row['客户物料代码']})相关数据`);

            item.manuDate = row['DateCode'];
            item.vendorBatch = row['批次号'];
            item.origin = row['产地'];
            item.mpq = row['数量'];
            item.odc = row['原DC'];
            item.labelType = labelType;
            item.printCount = row['标签数量'];
            item.remark = row['备注'];
            console.log('提交标签数据', item);

            const res = await rootVue.$api.srm.addNewlabelCodeInfo(item);
            if (!res?.data?.id) {
                throw new Error(`添加标签失败,第${i + 1}条数据`);
            }

            const listIds = [];
            let pageNum = 1;
            let pageSize = 10;
            let maxPages = 1000;
            while (pageNum <= maxPages) {
                const idItem = await rootVue.$api.srm.getNewLabelCodeDetail({
                    infoid: res.data.id,
                    pageNum,
                    pageSize
                });

                if (!idItem?.records?.length) {
                    throw new Error(`获取Uid失败,第${i + 1}条数据`);
                }

                idItem.records.forEach(v => listIds.push(v.id));

                const total = idItem.total || 0;
                maxPages = idItem.pages || 0;

                if (listIds.length < total) {
                    pageNum++;
                    await waitTime(50);
                } else {
                    break;
                }
            }

            labelIds.push(...new Set(listIds));
            loading.text = `数据处理中（${Math.floor((i + 1) / keys.length * 100)}%）...`;

            await waitTime(300);
        }
    }

    function getOrigin(origin) {
        const item = originList.find(v => v.originName.toLocaleLowerCase() === origin.toLocaleLowerCase()) || {};
        return item.originName;
    }

    function getTableHtml(data) {
        const values = Object.values(data);
        const keys = Object.keys(values[0]);
        let labelTotal = 0;

        const th = keys.map(function (key) {
            return `<th>${key}</th>`;
        }).join('');

        const tr = values.map((val, i) => {
            const row = keys.map(function (key) {
                if (key == '标签数量') {
                    labelTotal += val[key];
                }
                if (key == '产地') {
                    const origin = getOrigin(val[key]);
                    const style = origin ? '' : `style="background: #ff8585;"`;
                    val[key] = origin || val[key] || '';
                    return `<td ${style}>${val[key]}</td>`;
                } else {
                    return `<td>${val[key] || ''}</td>`;
                }
            });
            return `<tr><td>${i + 1}</td>${row.join('')}</tr>`;
        });

        const style = document.createElement('style');
        style.textContent = `
.my-table { width: fit-content;min-width:420px;max-width:85vw; }
.my-table .el-message-box__message{max-height: 85vh; overflow: auto;}
`;
        document.head.appendChild(style);

        return `
<div <span style="font-weight: bold;">批量导入${labelType == 'PQ' ? 'PQ内箱' : 'CQ外箱'}标签</h3>
<div>生成 <span style="color:red;font-weight: bold;">${tr.length}</span> 条数据，<span style="color:red;font-weight: bold;">${labelTotal}</span>个标签。请检查表格数据是否有误，特别是<span style="color:red;font-weight: bold;">红色</span>部分。</div>
<table border>
    <thead>
        <tr><th>序号</th>${th}</tr>
    </thead>
    <tbody>${tr.join('')}</tbody>
</table>`
    }

    function openLabelPage() {
        if (!labelIds.length) return;
        const url = window.location.origin + `/srm-finance/newLabelcodeInfo/downLoadPdfLabel?labelType=${labelType}&hqUids=${labelIds.join(',')}`;
        console.log('标签地址', url);
        /** pdf地址 /srm-finance/newLabelcodeInfo/downLoadPdfLabel?labelType=CQ&hqUids=eebe41627cda4ade758533772180bbe5,ed6359e064f10ce2468821107e099421 */
        window.open(url);
    }


    function loadXLSX(callback) {
        if (window.XLSX) {
            console.log('xlsx 库加载完成');
            callback();
        } else {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
            script.onload = () => {
                console.log('xlsx 库加载完成');
                callback();
            };
            script.onerror = () => {
                console.error('无法加载 xlsx 库');
            };
            document.head.appendChild(script);
        }
    }

    function waitTime(time = 500) {
        return new Promise(resolve => {
            setTimeout(resolve, time);
        });
    }

    function createFileInput() {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.xlsx,.xls';
        fileInput.id = 'excelFile';
        fileInput.style.display = 'none';
        fileInput.click();
        return fileInput;
    }

    function setupFileReader(inputElement) {
        return new Promise((resolve, reject) => {
            inputElement.addEventListener('change', function (e) {
                const file = e.target.files[0];
                if (!file) return;

                const reader = new FileReader();
                reader.onload = function (event) {
                    try {
                        const data = new Uint8Array(event.target?.result);
                        const workbook = XLSX.read(data, { type: 'array' });

                        const sheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[sheetName];

                        const jsonData = XLSX.utils.sheet_to_json(worksheet);

                        console.log('解析结果：', jsonData);
                        resolve(jsonData);
                    } catch (error) {
                        console.error('解析 Excel 出错：', error);
                        reject(error);
                    }
                };

                reader.readAsArrayBuffer(file);
            });
        });
    }

    function waitForSelector(selector, expectedText = null, timeout = 60000) {
        return new Promise((resolve, reject) => {
            let timeoutId;

            const matchElement = () => {
                const elements = document.querySelectorAll(selector);
                for (const el of elements) {
                    const text = el.textContent.trim();
                    if (!expectedText) {
                        return el;
                    } else if (typeof expectedText === 'string' && text.includes(expectedText)) {
                        return el;
                    } else if (expectedText instanceof RegExp && expectedText.test(text)) {
                        return el;
                    }
                }
                return null;
            };

            const existingEl = matchElement();
            if (existingEl) {
                resolve(existingEl);
                return;
            }

            const observer = new MutationObserver(() => {
                const matchedEl = matchElement();
                if (matchedEl) {
                    observer.disconnect();
                    clearTimeout(timeoutId);
                    resolve(matchedEl);
                }
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true,
                characterData: true
            });

            timeoutId = setTimeout(() => {
                observer.disconnect();
                reject(new Error(`Timeout: 未找到符合 "${expectedText}" 的选择器 "${selector}"`));
            }, timeout);
        });
    }
}